<template>
  <a-upload
    name="img"
    list-type="picture-card"
    :show-upload-list="showUploadList"
    :action="imgUploadUrl"
    :headers="headers"
    :file-list="fileList"
    :multiple="true"
    :before-upload="beforeUpload"
    @change="normFileList"
    @preview="onPreview"
    :remove="handleRemove"
    v-if="!isVideo && multiple"
  >
    <a-icon type="plus" />
    <pre-modal ref="preModal" />
  </a-upload>
  <a-upload
    name="img"
    list-type="picture-card"
    :action="imgUploadUrl"
    :show-upload-list="false"
    :headers="headers"
    :before-upload="beforeUpload"
    @change="normFile"
    v-else-if="!isVideo && !multiple"
  >
    <template>
      <img class="upload-avatar" v-if="!loading && value" :src="value" alt="avatar" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <span class="upload-text">{{ text }}</span>
      </div>
    </template>
  </a-upload>
  <a-upload
    name="img"
    list-type="picture-card"
    :action="imgUploadUrl"
    :show-upload-list="false"
    :headers="headers"
    @change="normFile"
    v-else-if="isVideo"
  >
    <template>
      <video class="upload-avatar" v-if="!loading && value" :src="value" alt="视频" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <span class="upload-text">{{ text }}</span>
      </div>
    </template>
  </a-upload>
</template>

<script>
import storage from 'store'
import { imgUploadUrl } from '@/api/upload'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import PreModal from '@/components/pre-modal'
export default {
  components: {
    PreModal
  },
  props: {
    value: {
      type: [Array, String],
      default: null
    },
    multiple: {
      type: Boolean,
      default: false
    },
    isVideo:{
      type: Boolean,
      default: false
    },
    showUploadList: {
      type: Boolean,
      default: true
    },
    text: {
      type: String,
      default: ''
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data () {
    return {
      imgUploadUrl,
      headers: {
        token: storage.get(ACCESS_TOKEN)
      },
      loading: false,
      fileList: []
    }
  },
  watch: {
    value: {
      handler (val) {
        if (val instanceof Array) {
          this.fileList = valToObjArr(val)
        }
        if (typeof val === 'string') {
          try {
            const newValList = JSON.parse(val)
            this.fileList = valToObjArr(newValList)
          } catch (error) {
            this.fileList = []
          }
        }

        function valToObjArr (val) {
          return val.map((item, index) => {
            if (typeof item === 'object') {
              return item
            } else {
              return {
                url: item,
                status: item ? 'done' : 'uploading',
                uid: item,
                name: item
              }
            }
          })
        }
      },
      immediate: true
    }
  },
  methods: {
    onPreview (e) {
      const previewImage = e.url || e.thumburl
      this.$refs.preModal.preview(previewImage)
    },
    normFile (e) {
      console.log('Upload event:', e)
      if (e.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (e.file.status === 'done') {
        this.loading = false
        const response = e.file.response
        if (response.status === 0) {
          this.$emit('change', response.data.img)
        } else {
          this.$message.warning(response.msg)
        }
      }
    },
    normFileList ({ fileList, file }) {
      if (file.status === 'uploading') {
        this.$emit('change', fileList)
        console.log('uploading', fileList)
      }
      if (file.status === 'done') {
        const response = file.response
        if (response.status === 0) {
          const newFileList = fileList.map(item => item.url || item.response.data.img)
          this.$emit('change', newFileList)
        } else {
          this.$message.warning(response.msg)
        }
      }
    },
    beforeUpload (file) {
      if(!this.isVideo){
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          // this.$message.error('你只能上传JPG|PNG文件!')
        }
        return isJpgOrPng
      }
    },
    handleRemove (file) {
      const newFileList = this.fileList.slice().map(item => item.url)
      const index = newFileList.findIndex(item => item === file.url)
      newFileList.splice(index, 1)
      this.$emit('change', newFileList)
    }
  }
}
</script>

<style lang="less" scoped>
.upload-avatar {
  border-radius: 5px;
  object-fit: cover;
  object-position: center;
  width: 100%;
  // height: 100%;
}
.upload-text{
  display: block;
  font-size: 12px;
  color:#999;
}
</style>
